<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.kw"
        placeholder="搜索生产单名称"
        style="width: 200px;"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.order_no"
        placeholder="订单单号"
        style="width: 200px; margin-left: 10px;"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
      />
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="success"
        icon="el-icon-refresh"
        @click="handleReset"
      >
        重置
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%; margin-top: 20px;"
    >
      <el-table-column label="ID" prop="id" align="center" width="80">
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="生产单名称" min-width="200">
        <template slot-scope="{ row }">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="关联订单" width="180">
        <template slot-scope="{ row }">
          <el-tag
            v-if="row.crm_order_no"
            type="primary"
            size="small"
            style="cursor: pointer;"
            @click="handleViewOrder(row)"
          >
            {{ row.crm_order_no }}
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>

      <el-table-column label="类型" width="150" align="center">
        <template slot-scope="{ row }">
          <el-tag
            :type="getStateTagType(row.state)"
            size="small"
          >
            {{ getStateLabel(row.state) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="唯一编码" width="200">
        <template slot-scope="{ row }">
          <span>{{ row.token || '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" width="160" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.created_at | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
        <template slot-scope="{ row }">
          <el-button
            type="primary"
            size="mini"
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button
            type="info"
            size="mini"
            @click="handleView(row)"
          >
            预览
          </el-button>
          <el-button
            v-if="row.token"
            type="success"
            size="mini"
            @click="handleCopyLink(row)"
          >
            复制链接
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-show="total > 0"
      :current-page="listQuery.page"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="listQuery.pagesize"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      style="margin-top: 20px;"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 生产单drawer -->
    <crmproductionorder
      :order_no="currentOrderNo"
      :order_name="currentOrderName"
      :token="currentToken"
      :visible="showProductionOrderDrawer"
      @close="showProductionOrderDrawer = false"
      @refresh="getList"
    />

    <!-- 订单详情drawer -->
    <crmorderdetail
      :order_data="currentOrder"
      :order-states="[]"
      :show-able="showOrderDetailDrawer"
      @close="showOrderDetailDrawer = false"
    />
  </div>
</template>

<script>
import { Get } from '@/api/crm/crmproductionorder'
import { parseTime } from '@/utils'
import Crmproductionorder from '@/views/crm/elements/crmproductionorder.vue'
import Crmorderdetail from '@/views/crm/elements/crmorderdetail.vue'

export default {
  name: 'ProductionOrderList',
  components: { Crmproductionorder, Crmorderdetail },
  filters: {
    parseTime
  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        pagesize: 20,
        kw: '',
        order_no: ''
      },
      stateOptions: [
        { value: '1', label: '询价单' },
        { value: '2', label: '样品生产' },
        { value: '3', label: '大货生产' },
        { value: '4', label: 'PI' }
      ],
      // 生产单drawer相关
      showProductionOrderDrawer: false,
      currentOrderNo: '',
      currentOrderName: '',
      currentToken: '', // 添加token参数
      // 订单详情drawer相关
      showOrderDetailDrawer: false,
      currentOrder: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      const params = new URLSearchParams()
      params.append('page', this.listQuery.page)
      params.append('pagesize', this.listQuery.pagesize)
      if (this.listQuery.kw) {
        params.append('kw', this.listQuery.kw)
      }
      if (this.listQuery.order_no) {
        params.append('order_no', this.listQuery.order_no)
      }

      Get('', params.toString()).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleReset() {
      this.listQuery = {
        page: 1,
        pagesize: 20,
        kw: '',
        order_no: ''
      }
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pagesize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    getStateLabel(state) {
      const option = this.stateOptions.find(o => o.value === state)
      return option ? option.label : state
    },
    getStateTagType(state) {
      const typeMap = {
        '1': 'info',
        '2': 'warning',
        '3': 'success',
        '4': 'primary'
      }
      return typeMap[state] || 'info'
    },
    handleEdit(row) {
      // 打开生产单编辑drawer，传递token
      this.currentOrderNo = row.crm_order_no || ''
      this.currentOrderName = row.name || ''
      this.currentToken = row.token || '' // 传递token
      this.showProductionOrderDrawer = true
    },
    handleView(row) {
      // 在新窗口预览生产单
      if (row.token) {
        // 使用po.lianf.com域名预览
        const url = `https://po.lianf.com/${row.token}`
        window.open(url, '_blank')
      } else {
        this.$message.warning('该生产单没有生成预览链接')
      }
    },
    handleViewOrder(row) {
      // 点击订单号，打开订单详情drawer
      if (!row.crmorder_data) {
        this.$message.warning('该生产单未关联订单或订单数据不完整')
        return
      }
      // 直接使用后端返回的订单数据
      this.currentOrder = JSON.parse(JSON.stringify(row.crmorder_data))
      this.showOrderDetailDrawer = true
    },
    handleCopyLink(row) {
      if (!row.token) {
        this.$message.warning('该生产单没有生成预览链接')
        return
      }
      // 使用po.lianf.com域名
      const url = `https://po.lianf.com/${row.token}`
      this.copyToClipboard(url)
      this.$message.success('链接已复制到剪贴板')
    },
    copyToClipboard(text) {
      const textarea = document.createElement('textarea')
      textarea.value = text
      textarea.style.position = 'fixed'
      textarea.style.opacity = '0'
      document.body.appendChild(textarea)
      textarea.select()
      document.execCommand('copy')
      document.body.removeChild(textarea)
    }
  }
}
</script>

<style scoped>
.filter-container {
  padding: 20px;
  background: #fff;
  margin-bottom: 20px;
}
.filter-item {
  margin-bottom: 10px;
}
</style>
